package org.example.web;

import org.example.util.VerifyCodeUtils;
import org.example.vo.Result;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * Company 源辰信息
 *
 * @author navy
 * @date 2024/5/31
 * Email haijunzhou@hnit.edu.cn
 */
@RestController
public class VcodeDo {
    @Resource
    JavaMailSender mailSender;

    @Value("${vcode.sendMail}")
    String myMail;

    @GetMapping("vcodeEmail")
    public Result sendUpPwdVcode(HttpSession session, String email){
        String vode = System.currentTimeMillis()+"";
        vode = vode.substring(vode.length() - 4);
        session.setAttribute("vcode", vode);
        // 文本邮件内容对象
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(myMail);
        message.setTo(email);
        message.setSubject("重置密码验证码");
        message.setText("您重置密码的验证码是: " + vode);
        mailSender.send(message);
        return Result.ok("验证码发送成功!");
    }

    @GetMapping(path="vcodeImage", produces = MediaType.IMAGE_PNG_VALUE)
    public void vcodeImage(HttpSession session,
            HttpServletResponse response) throws IOException {
        String vcode = VerifyCodeUtils.outputImage(response);
        session.setAttribute("vcode", vcode);
    }
}
